﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TCMS.Models;
using TCMS.Models.DAO;
using System.Web.Script.Serialization;

namespace tcms.Controllers
{
    [Authorize(Roles = "staff, manager")]
    public class TaskController : Controller
    {
        private TaskDAO _taskDAO = DAOFactory.getTaskDAO();
        private ShopFloorDAO _shopFloorDAO = DAOFactory.getShopFloorDAO();

        //
        // GET: /Task/

        public ActionResult Index()
        {
            ViewBag.ShopFloors = _shopFloorDAO.getShopFloors().Where(o => o.Status != 2).OrderBy(m => m.ShopName);

            return View();
        }

        //
        // GET: /Task/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Task/Create

        [HttpPost]
        public ActionResult Create(TaskEntity task)
        {
            try
            {
                task.CreateBy = HttpContext.User.Identity.Name;
                List<TaskEntity> result = _taskDAO.addNewTask(task);
                //todo @Hongfei: if result is not null, the show all conflict tasks; else display sth.
                if (result != null && result.Count > 0)
                {
                    Response.StatusCode = 500;
                    return PartialView("Confilict", result);
                }
                else
                {
                    return Content("创建成功");
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
        }

        public JsonResult Search(int? page, int? pagesize, DateTime? from, DateTime? to)
        {
            var tasks = _taskDAO.Search(page, pagesize, null, null, null, from, to);

            var data = new { Total = tasks.Count, Rows = tasks };

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Status(int id)
        {
            TaskEntity task = null;
            try
            {
                task = _taskDAO.GetSingleTaskById(id);
            }
            catch (Exception ex)
            {
            }
            return View(task);
        }
    }
}
